﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kangaroo.Model;

namespace Kangaroo.Shell
{
    class EventViewManager
    {
        private const string _imgKeyInfo = "info";
        private const string _imgKeyWarning = "warning";
        private const string _imgKeyError = "error";
        private readonly ListView _listView;

        public EventViewManager(ListView listView)
        {
            _listView = listView;
            var imageList = new ImageList();
            imageList.Images.Add(_imgKeyInfo, Resource.info);
            imageList.Images.Add(_imgKeyWarning, Resource.warning);
            imageList.Images.Add(_imgKeyError, Resource.error);
            _listView.SmallImageList = imageList;
        }

        public void RecordEvent(string eventText)
        {
            RecordRow(DateTime.Now, eventText);
        }

        private void RecordRow(DateTime time, string eventText, string imageKey = null)
        {
            if (_listView.InvokeRequired)
            {
                _listView.Invoke(new MethodInvoker(delegate
                    {
                        RecordRow(time, eventText, imageKey);
                    }));
            }
            else
            {
                if (_listView.Items.Count >= 1000)
                {
                    _listView.Items.RemoveAt(_listView.Items.Count - 1);
                }
                _listView.Items.Insert(0, new ListViewItem(new[] 
                        {
                            time.ToString(), 
                            eventText 
                        }, imageKey));
            }

        }

        public void RecordAlarm(AlarmInfo alarm)
        {
            RecordRow(alarm.AlarmTime, alarm.ToString(),
                AlarmLevelToImageKey(alarm.AlarmLevel));
        }

        private static string AlarmLevelToImageKey(byte alarmLevel)
        {
            switch(alarmLevel)
            {
                case 0:
                    return _imgKeyInfo;
                case 1:
                case 2:
                case 3:
                case 4:
                    return _imgKeyWarning;
                case 5:
                    return _imgKeyError;
                default:
                    throw new ArgumentOutOfRangeException("alarmLevel");
            }
        }
    }
}
